import React, { useEffect, useRef, useState } from 'react'
import { Card, Row, Col, Tag, Divider } from 'antd'
import './Home.scss'
import * as echarts from 'echarts'

const SummaryItem: React.FC<{ label: string; value: string | number; right?: React.ReactNode }> = ({ label, value, right }) => {
  return (
    <div className="summary-item">
      <div className="label">
        {label}
        <span className="value-inline">{value}</span>
      </div>
      {right && <div className="right-action">{right}</div>}
    </div>
  )
}

const LegendRow: React.FC<{ color: string; name: string; value: number | string }> = ({ color, name, value }) => (
  <div className="legend-row">
    <span className="dot" style={{ backgroundColor: color }} />
    <span className="name">{name}</span>
    <span className="spacer" />
    <span className="number">{value}</span>
  </div>
)

export default function Home() {
  const qtyRef = useRef<HTMLDivElement>(null)
  const amtRef = useRef<HTMLDivElement>(null)
  const statsRef = useRef<HTMLDivElement>(null)
  const [activeTab, setActiveTab] = useState('1year')
  const outStatsRef = useRef<HTMLDivElement>(null)
  const [outActiveTab, setOutActiveTab] = useState('7days')

  useEffect(() => {
    const qtyChart = qtyRef.current ? echarts.init(qtyRef.current) : null
    const amtChart = amtRef.current ? echarts.init(amtRef.current) : null
    const statsChart = statsRef.current ? echarts.init(statsRef.current) : null

    const commonSeries = (data: { value: number; name: string }[]) => ({
      type: 'pie',
      radius: ['60%', '85%'],
      center: ['50%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: { borderRadius: 6, borderColor: '#fff', borderWidth: 2 },
      label: { show: false },
      labelLine: { show: false },
      data
    })

    const qtyData = [
      { value: 567, name: '仓库一' },
      { value: 678, name: '仓库二' },
      { value: 456, name: '仓库三' },
      { value: 789, name: '仓库四' },
      { value: 567, name: '仓库五' },
      { value: 345, name: '仓库六' },
      { value: 678, name: '仓库七' }
    ]
    const qtyTotal = qtyData.reduce((s, i) => s + Number(i.value), 0)

    qtyChart?.setOption({
      color: ['#5B8FF9', '#61DDAA', '#657797', '#F6BD16', '#7262fd', '#78D3F8', '#F08BB4'],
      graphic: [
        {
          type: 'group',
          left: 'center',
          top: 'center',
          children: [
            {
              type: 'text',
              top: -20,
              style: {
                text: String(qtyTotal),
                textAlign: 'center',
                textVerticalAlign: 'top',
                fill: '#3f536e',
                fontSize: 22,
                fontWeight: 700
              }
            },
            {
              type: 'text',
              top: 10,
              style: {
                text: '总库存',
                textAlign: 'center',
                textVerticalAlign: 'middle',
                fill: 'rgba(0, 0, 0, 0.45)',
                fontSize: 15
              }
            }
          ]
        }
      ],
      series: [
        commonSeries(qtyData)
      ]
    })

    const amtData = [
      { value: 539.0, name: '仓库一' },
      { value: 920.0, name: '仓库二' },
      { value: 995.0, name: '仓库三' },
      { value: 687.0, name: '仓库四' },
      { value: 178.0, name: '仓库五' },
      { value: 867.0, name: '仓库六' },
      { value: 120.0, name: '仓库七' }
    ]
    const amtTotal = amtData.reduce((s, i) => s + Number(i.value), 0).toFixed(0)

    amtChart?.setOption({
      color: ['#5B8FF9', '#61DDAA', '#657797', '#F6BD16', '#7262fd', '#78D3F8', '#F08BB4'],
      graphic: [
        {
          type: 'group',
          left: 'center',
          top: 'center',
          children: [
            {
              type: 'text',
              top: -20,
              style: {
                text: String(amtTotal),
                textAlign: 'center',
                textVerticalAlign: 'middle',
                fill: '#3f536e',
                fontSize: 22,
                fontWeight: 700
              }
            },
            {
              type: 'text',
              top: 10,
              style: {
                text: '总金额',
                textAlign: 'center',
                textVerticalAlign: 'middle',
                fill: 'rgba(0,0,0,0.45)',
                fontSize: 15
              }
            }
          ]
        }
      ],
      series: [
        commonSeries(amtData)
      ]
    })

    const handleResize = () => {
      qtyChart?.resize()
      amtChart?.resize()
      statsChart?.resize()
    }
    window.addEventListener('resize', handleResize)

    return () => {
      window.removeEventListener('resize', handleResize)
      qtyChart?.dispose()
      amtChart?.dispose()
      statsChart?.dispose()
    }
  }, [activeTab])

  // 统计数据
  const getStatsData = (period: string) => {
    const dataMap = {
      '7days': {
        dates: ['2023-08-01', '2023-08-02', '2023-08-03', '2023-08-04', '2023-08-05', '2023-08-06', '2023-08-07'],
        quantity: [22, 100, 145, 105, 60, 115, 110],
        amount: [275, 800, 900, 650, 500, 850, 750]
      },
      '30days': {
        dates: Array.from({ length: 30 }, (_, i) => `${i + 1}`),
        quantity: [20, 95, 135, 145, 95, 85, 135, 145, 85, 110, 95, 85, 95, 85, 140, 145, 95, 85, 135, 145, 85, 105, 100, 95, 85, 95, 135, 145, 95, 85],
        amount: [350, 600, 900, 1050, 500, 800, 900, 400, 900, 500, 600, 900, 900, 700, 400, 350, 400, 500, 800, 400, 600, 700, 600, 800, 300, 800, 900, 500, 800, 300]
      },
      '1year': {
        dates: ['2023-01', '2023-02', '2023-03', '2023-04', '2023-05', '2023-06', '2023-07', '2023-08', '2023-09', '2023-10', '2023-11', '2023-12'],
        quantity: [20, 95, 135, 140, 95, 85, 130, 20, 128, 110, 105, 95],
        amount: [400, 600, 1050, 1100, 700, 400, 1000, 400, 1000, 500, 550, 950]
      }
    }
    return dataMap[period as keyof typeof dataMap] || dataMap['7days']
  }

  // 渲染统计图表
  useEffect(() => {
    const statsChart = statsRef.current ? echarts.init(statsRef.current) : null
    if (!statsChart) return

    const data = getStatsData(activeTab)
    console.log('当前数据:', data) // 调试用

    statsChart.setOption({
      legend: {
        data: ['数量', '金额'],
        top: 0,
        left: 'center',
        itemGap: 20,
        textStyle: { fontSize: 14, color: '#000' }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' }
      },
      grid: {
        left: '8%',
        right: '8%',
        top: '15%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.dates,
        axisLine: { lineStyle: { color: '#e5e5e5' } },
        axisTick: { show: false },
        axisLabel: { color: '#666', fontSize: 12 }
      },
      yAxis: [
        {
          type: 'value',
          name: '数量',
          position: 'left',
          min: 0,
          max: 175,
          interval: 25,
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { color: '#666', fontSize: 12 },
          nameTextStyle: { color: '#666', fontSize: 12 },
          splitLine: { lineStyle: { color: '#f0f0f0' } }
        },
        {
          type: 'value',
          name: '金额',
          position: 'right',
          min: 0,
          max: 1200,
          interval: 200,
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { color: '#666', fontSize: 12 },
          nameTextStyle: { color: '#666', fontSize: 12 },
          splitLine: { show: false }
        }
      ],
      series: [
        {
          name: '数量',
          type: 'bar',
          yAxisIndex: 0,
          data: data.quantity,
          itemStyle: { color: '#4A70E0' },
          barWidth: '60%'
        },
        {
          name: '金额',
          type: 'line',
          yAxisIndex: 1,
          data: data.amount,
          lineStyle: { color: '#82C91E', width: 2 },
          itemStyle: { color: '#82C91E', borderWidth: 2, borderColor: '#fff' },
          symbol: 'circle',
          symbolSize: 6
        }
      ]
    })

    return () => statsChart.dispose()
  }, [activeTab])

  // 渲染出库统计图表（橙色）
  useEffect(() => {
    const chart = outStatsRef.current ? echarts.init(outStatsRef.current) : null
    if (!chart) return

    const data = getStatsData(outActiveTab)

    chart.setOption({
      legend: { data: ['数量', '金额'], top: 0, left: 'center', itemGap: 20, textStyle: { fontSize: 14, color: '#000' } },
      tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
      grid: { left: '8%', right: '8%', top: '15%', bottom: '10%', containLabel: true },
      xAxis: { type: 'category', data: data.dates, axisLine: { lineStyle: { color: '#e5e5e5' } }, axisTick: { show: false }, axisLabel: { color: '#666', fontSize: 12 } },
      yAxis: [
        { type: 'value', name: '数量', position: 'left', min: 0, max: 175, interval: 25, axisLine: { show: false }, axisTick: { show: false }, axisLabel: { color: '#666', fontSize: 12 }, nameTextStyle: { color: '#666', fontSize: 12 }, splitLine: { lineStyle: { color: '#f0f0f0' } } },
        { type: 'value', name: '金额', position: 'right', min: 0, max: 1200, interval: 200, axisLine: { show: false }, axisTick: { show: false }, axisLabel: { color: '#666', fontSize: 12 }, nameTextStyle: { color: '#666', fontSize: 12 }, splitLine: { show: false } }
      ],
      series: [
        { name: '数量', type: 'bar', yAxisIndex: 0, data: data.quantity, itemStyle: { color: '#F6BD16' }, barWidth: '60%' },
        { name: '金额', type: 'line', yAxisIndex: 1, data: data.amount, lineStyle: { color: '#82C91E', width: 2 }, itemStyle: { color: '#82C91E', borderWidth: 2, borderColor: '#fff' }, symbol: 'circle', symbolSize: 6 }
      ]
    })

    return () => chart.dispose()
  }, [outActiveTab])

  return (
    <div className="home">
      <Card variant="outlined" className="panel panel-summary">
        <Row gutter={24}>
          <Col span={12} className="summary-wrap">
            <div className="panel-title">今日概况</div>
            <Row gutter={24}>
              <Col span={12} className="summary-col left">
                <SummaryItem label="单据数量" value={52} right={<Tag color="#95de64">入库</Tag>} />
                <Divider className="v-divider" />
                <SummaryItem label="入库数量" value={602} />
                <Divider className="v-divider" />
                <SummaryItem label="入库金额" value={"2,000.00"} />
              </Col>
              <Col span={12} className="summary-col">
                <SummaryItem label="单据数量" value={52} right={<Tag color="#ffd666">出库</Tag>} />
                <Divider className="v-divider" />
                <SummaryItem label="出库数量" value={602} />
                <Divider className="v-divider" />
                <SummaryItem label="出库金额" value={"2,000.00"} />
              </Col>
            </Row>
          </Col>
          <Col span={12} className="summary-wrap">
            <div className="panel-title">昨日概况</div>
            <Row gutter={24}>
              <Col span={12} className="summary-col left">
                <SummaryItem label="单据数量" value={52} right={<Tag color="#95de64">入库</Tag>} />
                <Divider className="v-divider" />
                <SummaryItem label="入库数量" value={602} />
                <Divider className="v-divider" />
                <SummaryItem label="入库金额" value={"2,000.00"} />
              </Col>
              <Col span={12} className="summary-col">
                <SummaryItem label="单据数量" value={52} right={<Tag color="#ffd666">出库</Tag>} />
                <Divider className="v-divider" />
                <SummaryItem label="出库数量" value={602} />
                <Divider className="v-divider" />
                <SummaryItem label="出库金额" value={"2,000.00"} />
              </Col>
            </Row>
          </Col>
        </Row>
      </Card>

      <Row gutter={24}>
        <Col span={12}>
          <Card variant="outlined" className="panel chart-card">
            <div className="panel-title">库存数量占比</div>
            <div className="chart-box">
              <div className="echart donut" ref={qtyRef} />
              <div className="legend">
                <LegendRow color="#5B8FF9" name="仓库一" value={567} />
                <LegendRow color="#61DDAA" name="仓库二" value={678} />
                <LegendRow color="#657797" name="仓库三" value={456} />
                <LegendRow color="#F6BD16" name="仓库四" value={789} />
                <LegendRow color="#7262fd" name="仓库五" value={567} />
                <LegendRow color="#78D3F8" name="仓库六" value={345} />
                <LegendRow color="#F08BB4" name="仓库七" value={678} />
              </div>
            </div>
          </Card>
        </Col>
        <Col span={12}>
          <Card variant="outlined" className="panel chart-card">
            <div className="panel-title">库存金额占比</div>
            <div className="chart-box">
              <div className="echart donut" ref={amtRef} />
              <div className="legend">
                <LegendRow color="#5B8FF9" name="仓库一" value={539.00} />
                <LegendRow color="#61DDAA" name="仓库二" value={920.00} />
                <LegendRow color="#657797" name="仓库三" value={995.00} />
                <LegendRow color="#F6BD16" name="仓库四" value={687.00} />
                <LegendRow color="#7262fd" name="仓库五" value={178.00} />
                <LegendRow color="#78D3F8" name="仓库六" value={867.00} />
                <LegendRow color="#F08BB4" name="仓库七" value={120.00} />
              </div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 入库统计图表 */}
      <Card variant="outlined" className="panel chart-card">
        <div className="stats-header">
          <div className="stats-title">入库统计</div>
          <div className="stats-tabs">
            <button
              className={`tab ${activeTab === '7days' ? 'active' : ''}`}
              onClick={() => setActiveTab('7days')}
            >
              最近7天
            </button>
            <button
              className={`tab ${activeTab === '30days' ? 'active' : ''}`}
              onClick={() => setActiveTab('30days')}
            >
              最近30天
            </button>
            <button
              className={`tab ${activeTab === '1year' ? 'active' : ''}`}
              onClick={() => setActiveTab('1year')}
            >
              最近一年
            </button>
          </div>
        </div>
        <div className="echart stats-chart" ref={statsRef} />
      </Card>

      {/* 出库统计图表（橙色） */}
      <Card variant="outlined" className="panel chart-card">
        <div className="stats-header">
          <div className="stats-title">出库统计</div>
          <div className="stats-tabs">
            <button className={`tab ${outActiveTab === '7days' ? 'active' : ''}`} onClick={() => setOutActiveTab('7days')}>最近7天</button>
            <button className={`tab ${outActiveTab === '30days' ? 'active' : ''}`} onClick={() => setOutActiveTab('30days')}>最近30天</button>
            <button className={`tab ${outActiveTab === '1year' ? 'active' : ''}`} onClick={() => setOutActiveTab('1year')}>最近一年</button>
          </div>
        </div>
        <div className="echart stats-chart" ref={outStatsRef} />
      </Card>
    </div>
  )
}
